# This test script performs the first of the benchmarks presented in
# the paper I am submitting to percom '10. The benchmark performs a
# sharpening, brightness adjustment, and contrast adjustment of the
# given input image. The input images used in the paper can be found
# in testdata/percom.

from __future__ import with_statement
import sys
import scavenger
from time import sleep, time

# Check command line args.
if len(sys.argv) < 2:
    print 'Usage: percom1.py imagefile [-i iterations]'
    sys.exit(1)

# Read in the image file.
with open(sys.argv[1], 'rb') as infile:
    image = infile.read()

# And also read in thumbnail version.
with open(sys.argv[1].replace('.jpg', '_thumb.jpg'), 'rb') as infile:
    thumb = infile.read()

# Check whether a number of test iterations is given.
iterations = 1
if '-i' in sys.argv:
    iterations = int(sys.argv[sys.argv.index('-i') + 1])

# Sleep for a little while to make sure that we discover
# the available surrogates.
sleep(2.0)

@scavenger.aprofilescavenge('len(#0)','len(#0)', store=True)
def sharpen(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    factor = 1.0 + float(factor)
    new_image = ImageEnhance.Sharpness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.aprofilescavenge('len(#0)','len(#0)', store=True)
def brightness(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.aprofilescavenge('len(#0)','len(#0)')
def contrast(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Contrast(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

# Run the test!
for x in range(0, iterations):
    # Thumbnail processing.
    print 'Thumb    =',
    start = time()
#    try:
    x = sharpen(thumb, 1.0)
    x = brightness(x, 1.1)
    contrast(x, 1.1)
#    except:
#        print 'error',
    stop = time()
    print stop - start

    # Original image.
    print 'Original =',
    start = time()
    try:
        result = sharpen(image, 1.0)
        result = brightness(result, 1.1)
        result = contrast(result, 1.1)
    except:
        print 'error',
    stop = time()
    print stop - start

# Write the result for possible inspection.
with open('result.jpg', 'wb') as outfile:
    outfile.write(result)

scavenger.shutdown()
